package cn.com.joco.dk.core.user;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.util.WebUtils;


public class UserFilter extends org.apache.shiro.web.filter.authc.UserFilter {

	

	@Override
	protected boolean isLoginRequest(ServletRequest request,
			ServletResponse response) {
		HttpServletRequest sRequest=(HttpServletRequest)request;
		String loginUrl="";
		String url=sRequest.getRequestURI();

		if(url.equals("/login")){
			loginUrl="/login";
		}else if(url.equals("/m/login")){
			loginUrl="/m/login";
		}else{
			loginUrl="/m/login";
		}
		return   pathsMatch(loginUrl, request);
	}

	

	@Override
	protected void redirectToLogin(ServletRequest request,
			ServletResponse response) throws IOException {
		String loginUrl = getLoginUrl();
		String module=getModule(request);
		if(module.equals("webby")){
			loginUrl="/login";
		}else{
			loginUrl="/m/login";
		}
	      WebUtils.issueRedirect(request, response, loginUrl);
	}
	
	String getModule(ServletRequest request){
		String module="";
		if(request instanceof HttpServletRequest){
			HttpServletRequest hRequest = (HttpServletRequest)request;
			Cookie cookies[]=hRequest.getCookies();
		if(cookies!=null)
			for(Cookie c:cookies){
				if("module".equals(c.getName()) ){
					module=c.getValue();
					break;
				}
			}
		}
		if("".equals(module)||module==null){
			module="webby";
		}
		return module;
	}
	
}
